/***********************************************************
 * Product Name: ExcelQuicker
 * Copyright (c)2005, Eunge
 * Author: Eunge
 * Web Site: www.eudev.net
 * Mail/MSN: eudev.net@yeah.net
 * ********************************************************/
using System;
using System.Reflection;

namespace ExcelQuicker.Framework
{
	/// <summary>
	/// Stands for VBA macro executor on excel template document.
	/// </summary>
	/// <remarks>
	/// If you consider execute VBA macro on the template excel document, please construct object of this class and add it to the EQWorksheet object.
	/// </remarks>
	public class EQVBAHooker: EQRangeBase
	{
		private string mVBAName;

		/// <summary>
		/// Initialize EQVBAHooker with a VBA macro's name on excel template document
		/// </summary>
		/// <param name="vbaName"></param>
		public EQVBAHooker(string vbaName)
		{
			this.mVBAName = vbaName;
		}

		/// <summary>
		/// Execute VBA macro on excel template document
		/// </summary>
		/// <param name="objWorksheet"></param>
		protected internal override void Output(Excel.Worksheet objWorksheet)
		{
			this.DoBeforeOperationEvent(objWorksheet);
			objWorksheet.Activate();
			EQVBAHooker.RunMacro(objWorksheet, this.mVBAName);
			this.DoAfterOperationEvent(objWorksheet);
		}
		
		/// <summary>
		/// Run VBA function on specialized worksheet of excel document
		/// </summary>
		/// <param name="objWorksheet">Excel.Worksheet interface</param>
		/// <param name="functionName">VBA function's name</param>
		/// <returns></returns>
		private static void RunMacro(Excel.Worksheet objWorksheet, string functionName)
		{
			try
			{
				object missing = System.Reflection.Missing.Value;
				objWorksheet.Application._Run2(functionName, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing,
					missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing,
					missing, missing, missing, missing, missing);
			}
			catch(Exception exp)
			{
				throw new EQException("EQ1041", exp, functionName);
			}
		}
	}
}
